package com.dmgis.hndz.common.utils;

import com.dmgis.hndz.common.constant.FileContentType;
import io.minio.*;
import io.minio.errors.*;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Component
@Slf4j
public class MinIOUtil {

    @Autowired
    private MinioClient minioClient;

    /**
     * 桶名称
     */
    @Value("${minio.bucketName}")
    private String bucketName;
 
    @Value("${minio.endpoint}")
    private String endpoint;


    @Value("${minio.readPath}")
    private String readPath;

 
    /**
     * putObject上传文件
     *
     * @param file 文件
     * @return filePath
     */
    public Map<String, String> putObject(MultipartFile file) throws IOException, ServerException, InsufficientDataException, InternalException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, XmlParserException, ErrorResponseException, InvalidBucketNameException {
        //文件名
        String originalFilename = file.getOriginalFilename();
        //文件流
        @Cleanup
        InputStream inputStream = file.getInputStream();
        //文件大小
        long size = file.getSize();
        //文件路径
        String filePath = createFilePath(originalFilename);
        //存储方法 putObject
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(filePath)
                .stream(inputStream, size, -1)
                .contentType(file.getContentType())
                .build());
 
        HashMap<String, String> result = new HashMap<>();
        result.put("filePath", filePath);
        result.put("fileUrl", endpoint + "/" + bucketName + "/" + filePath);
        result.put("fileName", getFileName(filePath));
        return result;
    }


    public Map<String, String> putObject(String fileCatalogue, MultipartFile file, String fileName) throws IOException, ServerException, InsufficientDataException, InternalException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, XmlParserException, ErrorResponseException, InvalidBucketNameException {
        //文件流
        @Cleanup
        InputStream inputStream = file.getInputStream();
        //文件大小
        long size = file.getSize();
        //文件路径
        String filePath = createFilePath(fileCatalogue,fileName);
        //存储方法 putObject
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(filePath)
                .stream(inputStream, size, -1)
                .contentType(file.getContentType())
                .build());
 
        HashMap<String, String> result = new HashMap<>();
        result.put("filePath", filePath);
        result.put("fileUrl", endpoint + "/" + bucketName + "/" + filePath);
        result.put("fileName", getFileName(filePath));
 
        return result;
    }

    public Map<String, String> putObject( byte[] data,String fileCatalogue, String fileName, FileContentType contentType) throws ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        @Cleanup
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);

        int size = byteArrayInputStream.available();

        //文件路径
        String filePath = createFilePath(fileCatalogue,fileName);
        //存储方法 putObject
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(filePath)
                .stream(byteArrayInputStream, size, -1)
                .contentType(contentType.getName())
                .build());

        HashMap<String, String> result = new HashMap<>();
        result.put("filePath", filePath);
        result.put("fileUrl", readPath + "/" + bucketName + "/" + filePath);
        result.put("fileName", getFileName(filePath));
        return result;

    }


    public Map<String, String> putObject( InputStream inputStream,String fileCatalogue, String fileName, FileContentType contentType) throws IOException, ServerException, InsufficientDataException, InternalException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, XmlParserException, ErrorResponseException, InvalidBucketNameException {
        long size = inputStream.available();
        //文件路径
        String filePath = createFilePath(fileCatalogue,fileName);
        //存储方法 putObject
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(filePath)
                .stream(inputStream, size, -1)
                .contentType(contentType.getName())
                .build());

        HashMap<String, String> result = new HashMap<>();
        result.put("filePath", filePath);
        result.put("fileUrl", readPath + "/" + bucketName + "/" + filePath);
        result.put("fileName", getFileName(filePath));
        return result;
    }

    public Map<String, String> putObject( InputStream inputStream, String fileName, FileContentType contentType) throws IOException, ServerException, InsufficientDataException, InternalException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, XmlParserException, ErrorResponseException, InvalidBucketNameException {
        long size = inputStream.available();
        //文件路径
        String filePath = createFilePath(fileName);
        //存储方法 putObject
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(filePath)
                .stream(inputStream, size, -1)
                .contentType(contentType.getName())
                .build());

        HashMap<String, String> result = new HashMap<>();
        result.put("filePath", filePath);
        result.put("fileUrl", endpoint + "/" + bucketName + "/" + filePath);
        result.put("fileName", getFileName(filePath));
        return result;
    }
 
    /**
     * 上传xlsx格式的Excel
     *
     * @param inputStream
     * @param fileName
     * @return
     */
    public Map<String, String> putXlsxExcelByStream(String fileCatalogue, InputStream inputStream, String fileName) throws IOException, ServerException, InsufficientDataException, InternalException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, XmlParserException, ErrorResponseException, InvalidBucketNameException {
        //文件大小
        //byte[] bytes = IOUtils.toByteArray(inputStream);
        //int length = bytes.length;
        long size = inputStream.available();
        //文件路径
        String filePath = createFilePath(fileCatalogue,fileName);
        //存储方法 putObject
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(filePath)
                .stream(inputStream, size, -1)
                .contentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                .build());
 
        HashMap<String, String> result = new HashMap<>();
        result.put("filePath", filePath);
        result.put("fileUrl", endpoint + "/" + bucketName + "/" + filePath);
        result.put("fileName", getFileName(filePath));
        return result;
    }
 
    /**
     * 下载文件
     *
     * @param filePath 文件路径
     */
    public void getObject(HttpServletResponse httpServletResponse, String filePath) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException, InvalidBucketNameException {
        String fileName = getFileName(filePath);
        InputStream inputStream = minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucketName)
                .object(filePath)
                .build());
        downloadFile(httpServletResponse, inputStream, fileName);
    }


    /**
     * 获取文件路径
     *
     * @param originalFilename 原始文件名称
     * @return FilePath
     */
    public String getFileUrl(String fileCatalogue, String originalFilename) {
        return readPath+"/"+bucketName+"/"+fileCatalogue + "/" + originalFilename;
    }

 
    /**
     * 获取文件路径
     *
     * @param originalFilename 原始文件名称
     * @return FilePath
     */
    public String createFilePath(String originalFilename) {
        return new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/" + originalFilename;
    }
 
    /**
     * 获取文件路径
     * fileCatalogue 文件目录
     * @param originalFilename 原始文件名称
     * @return FilePath
     */
    public String createFilePath(String fileCatalogue, String originalFilename) {
        return fileCatalogue + "/" + originalFilename;
    }
 
    /**
     * 根据文件路径获取文件名称
     *
     * @param filePath 文件路径
     * @return 文件名
     */
    public String getFileName(String filePath) {
        String[] split = StringUtils.split(filePath, "/");
        return split[split.length - 1];
    }


    /**
     * 判断文件是否存在
     * @param objectName 文件名
     * @return
     */
    public  boolean isObjectExist(String objectName) {
        boolean exist = true;
        try {
            minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
        } catch (Exception e) {
            exist = false;
        }
        return exist;
    }

    /**
     * 判断文件是否存在
     * @param bucketName 存储桶
     * @param objectName 文件名
     * @return
     */
    public  boolean isObjectExist(String bucketName, String objectName) {
        boolean exist = true;
        try {
            minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
        } catch (Exception e) {
            exist = false;
        }
        return exist;
    }



    /**
     * 下载文件
     *
     * @param httpServletResponse httpServletResponse
     * @param inputStream         inputStream
     * @param fileName            文件名
     * @throws IOException IOException
     */
    public void downloadFile(HttpServletResponse httpServletResponse, InputStream inputStream, String fileName) throws IOException {
        //设置响应头信息，告诉前端浏览器下载文件
        httpServletResponse.setContentType("application/octet-stream;charset=UTF-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        //获取输出流进行写入数据
        OutputStream outputStream = httpServletResponse.getOutputStream();
        // 将输入流复制到输出流
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        // 关闭流资源
        inputStream.close();
        outputStream.close();
    }
 
 
    /**
     * 通过路径获取文件流
     *
     * @param filePath 文件路径
     * @return
     */
    public InputStream getFileInputStream(String filePath) {
        InputStream stream = null;
        try {
            ObjectStat statObjectResponse =
                    minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(filePath).build());
  		    //以流的形式获取一个文件对象
            if (statObjectResponse != null ) {
                stream = minioClient.getObject(
                        GetObjectArgs.builder()
                                .bucket(bucketName)
                                .object(filePath)
                                .build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stream;
    }


    /**
     * 通过url获取文件流
     *
     * @param filePath 文件路径
     * @return
     */
    public InputStream getFileInputStreamByUrl(String filePath) {
        InputStream stream = null;
        try {
            URL url = new URL(endpoint + "/" + bucketName + "/" + filePath);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            stream = connection.getInputStream();
        } catch (Exception e) {
            log.error("通过url获取文件流异常:" + e.getMessage());
        }
        return stream;
    }


    /**
     * 删除文件
     *
     * @param filePath 文件路径
     * @return
     */
    public void removeFile(String filePath) {
        try {
            //判断桶是否存在
            boolean res = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (res) {
                //删除文件
                minioClient.removeObject(RemoveObjectArgs.builder()
                        .bucket(bucketName)
                        .object(filePath)
                        .build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


 
}